package com.example.demo.handle;

import com.example.demo.domain.ScoreSheet;
import com.example.demo.domain.Student;
import com.example.demo.test.DataGenerator;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class EmailSender {

    @Value("${spring.mail.host}")
    private String host;
    @Value("${spring.mail.port}")
    private Integer port;
    @Value("${spring.mail.username}")
    private String username;
    @Value("${spring.mail.password}")
    private String password;

    public void sendScoreSheet() throws EmailException {
        ScoreSheet scoreSheet = DataGenerator.generateScoreSheet();
        HtmlEmail email = new HtmlEmail();
        email.setHostName(host);
        email.setSmtpPort(port);
        email.setAuthentication(username, password);
        email.setSSLOnConnect(true);
        email.setFrom(username);
        email.setSubject("学生成绩表");
        StringBuilder htmlBody = new StringBuilder("<html><body><table border='1'><tr><th>姓名</th><th>数学成绩</th><th>英语成绩</th><th>语文成绩</th></tr>");
        for (Student student : scoreSheet.getStudents()) {
            htmlBody.append("<tr><td>").append(student.getName()).append("</td><td>")
                   .append(student.getMathScore()).append("</td><td>")
                   .append(student.getEnglishScore()).append("</td><td>")
                   .append(student.getChineseScore()).append("</td></tr>");
        }
        htmlBody.append("</table></body></html>");
        email.setHtmlMsg(htmlBody.toString());
        email.setCharset("UTF-8");
        email.addTo("15192458230@163.com");
        email.send();
    }
}